package com.jr.controller;


import com.google.gson.Gson;
import com.jr.entity.User;
import com.jr.service.UserService;
import org.apache.maven.model.Model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


/**
 * 用户信息表
 *
 * @author Snoopy
 * @since 1.0.0 2022-12-31
 */
@Controller

public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 用户注册
     */
    @RequestMapping(value = "registUser.do", produces = "text/html;charset=utf-8")
    public @ResponseBody String  registUser(User user,HttpServletRequest request) {
        System.out.println(user);
        user.setUid(String.valueOf(System.currentTimeMillis()));
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("userx", user);
        modelAndView.setViewName("login.jsp");
        userService.addUser(user);
        User getuserx = userService.getuser(user);
        request.getSession().setAttribute("userx",getuserx);
        return new Gson().toJson(getuserx);

    }

    /**
     * 用户账号验证
     */
    @RequestMapping(value = "verificationUser.do", produces = "text/html;charset=utf-8")
    public @ResponseBody String verificationUser(User user) {
        User getuser = userService.getuser(user);

        if (getuser != null) {
            String s = new Gson().toJson(getuser);
            System.out.println(s);
            return s;
        }
        return null;
    }

    /**
     * 用户登录
     */
    @RequestMapping(value = "loginCheckUser.do", produces = "text/html;charset=utf-8")
    public @ResponseBody String loginCheckUser(User user, HttpServletRequest request) {

        User getuser = userService.getuser(user);
        System.out.println(getuser);
        if (getuser != null) {
            HttpSession session = request.getSession();
            session.setAttribute("user", getuser);
            return new Gson().toJson(getuser);
        }
        return null;
    }

    /**
     * 用户信息更新
     */
    @RequestMapping(value = "upadteUserInfo.do", produces = "text/html;charset=utf-8")
    public @ResponseBody String upadteUserInfo(User user) {
        int i = userService.modify(user);
        return i + "";
    }

    /**
     * 用户退出
     */
    @RequestMapping(value = "exit.do", produces = "text/html;charset=utf-8")
    public ModelAndView exit(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.setAttribute("user", null);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index.jsp");
        return modelAndView;
    }
}